package j.framework.tags.form;

import j.util.ConvertUtils;
import j.util.StringUtils;

import javax.servlet.jsp.JspException;

/**
 * User: jason
 * Date: 2014/12/18 12:53
 */
public class CheckboxTag extends BaseInputTag {

    private String label;
    private Boolean checked;
    private String onChange;

    @Override
    public String getInputType() {
        return "checkbox";
    }

    @Override
    public void writeFormTagBegin(FormTagWriter writer) throws JspException {
        if(StringUtils.isNotEmpty(label)){
            writer.writeSomething("<label>");
        }
        writer.beginTag("input");
    }

    @Override
    public void endBeginTag(FormTagWriter writer)  throws JspException{
        writer.closeBlankTag();
        if(StringUtils.isNotEmpty(label)){
            writer.writeSomething(label);
            writer.writeSomething("</label>");
        }
    }

    /**
     * 给标签增加value属性
     * @param writer
     * @param value form中此属性所对应的值
     * @throws JspException
     */
    @Override
    public void writeInputTagValue(FormTagWriter writer, Object value) throws JspException {
        if(checked!=null && checked){
            writer.writeSomething(" checked ");
        }
        if(null == value){
            value = getFormDataValue();
        }else{
            writer.writeSomething(" value=\"");
            writer.writeSomething(String.valueOf(value));
            writer.writeSomething("\"");
        }
        if(null!=value){
            if(checked == null && value instanceof Boolean){
                Boolean b = (Boolean)value;
                if(b){
                    writer.writeSomething(" checked ");
                }
            }else if(checked == null){
                Boolean b = ConvertUtils.toBoolean(String.valueOf(value));
                if(b){
                    writer.writeSomething(" checked ");
                }
            }
        }
    }

    @Override
    public void writeFormTagProperties(FormTagWriter writer) throws JspException {
        super.writeFormTagProperties(writer);
        writer.writeFormTagProperty("onchange",onChange);
    }

    @Override
    public String getCssClassName() {
        return null;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public void setChecked(Boolean checked) {
        this.checked = checked;
    }

    public void setOnChange(String onChange) {
        this.onChange = onChange;
    }
}
